<template>
    <canvas id="myCanvas" width="1700" height="820" ref="cvs"></canvas>
</template>

<script lang="ts" setup>
import { Utils } from "@/utils";
import { onMounted, ref } from "vue";
import { FontFamily } from "../Constants";
import GridSystem from "../GridSystem";
import { Map } from "../map/map.js";
import { Geographica } from "../map/geographica.js";

const cvs = ref(null);
let gls = ref<GridSystem | null>(null);

onMounted(() => {
    reset();
})

function reset(clear = false) {
    if (clear) localStorage.setItem("features", '');
    if (gls.value) {
        gls.value.destroy();
        gls.value = null;
    }
    let canvasDom = cvs.value as unknown as HTMLCanvasElement;
    const gridSys = new GridSystem(canvasDom);
    gridSys.initEventListener();
    gridSys.loadFont(FontFamily.SHISHANG);
    gridSys.draw(true)
    gls.value = gridSys;

    const map = new Map(gls.value.ctx.canvas.width, gls.value.ctx.canvas.height, new Geographica(120.07, 30.67), 5);
    gls.value.domElement.parentNode?.appendChild(map.domElement);
    map.domElement.style.position = "fixed";
    map.domElement.style.left = "0";
    map.domElement.style.top = "0";
    map.domElement.style.zIndex = "-1";
    map.update();

    document.addEventListener('mousedown', e => {
        let { x: x0, y: y0 } = Utils.getMousePos(map.domElement, e)
        x0 += map.pixelCenter.x;
        y0 += map.pixelCenter.y;
        let lastMove = { x: x0, y: y0 }
        function mousemove(ev: any) {
            let { x: x1, y: y1 } = Utils.getMousePos(map.domElement, ev)
            x1 += map.pixelCenter.x;
            y1 += map.pixelCenter.y;
            if (lastMove.x && lastMove.y) {
                let dx = x0 - x1;
                let dy = y0 - y1;
                // 修改地图中心点的地图像素坐标
                map.pixelCenter.x += dx;
                map.pixelCenter.y += dy;
                // 修改地图的LOD
                // 跟新地图状态的函数
                map.updateState();
                // 更新地图数据并绘制地图数据
                map.update();
            }
            lastMove.x = x1;
            lastMove.y = y1;
        }
        document.addEventListener('mousemove', mousemove);
        document.addEventListener("mouseup", () => {
            document.removeEventListener('mousemove', mousemove)
        })
    });

}

function setSize(canvasDom: HTMLCanvasElement) {
    canvasDom.width = document.documentElement.clientWidth - 4;
    canvasDom.height = document.documentElement.clientHeight - 4;

    window.onresize = () => {
        canvasDom.width = document.documentElement.clientWidth - 4;
        canvasDom.height = document.documentElement.clientHeight - 4;
    }
}

</script>